#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/17 9:18
# @Author  : JY.Liu
# @Site    : http://github.com/lh1993
# @Mail    : lhln0119@163.com
# @File    : redis_manager.py
# @Software: PyCharm

import requests
import json
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_DIR = os.path.join(BASE_DIR, "config")
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")

with open(CONFIG_FILE, 'rb') as f:
    config = json.load(f)

class RedisManager(object):

    def __init__(self):
        self.redis_manager_domain = config['redis-manager']['host']
        self.session = requests.Session()
        self.headers = {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=UTF-8",
            "Connection": "keep-alive",
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
        }

    def login(self):
        """登录redis-manager

        :return:
        """
        url = self.redis_manager_domain + "/user/login"
        data = {
            "userName": config['redis-manager']['username'],
            "password": config['redis-manager']['password']
        }
        res = self.session.post(
            url=url,
            data=json.dumps(data),
            headers=self.headers)
        print("登录redis-manager系统", flush=True)
        print(res.json(), flush=True)
        print(res.status_code, flush=True)
        return res.json()

    def get_group_list(self):
        """获取组列表

        :return:
        """
        url = self.redis_manager_domain + "/group/getGroupList"
        data = {
            "groupId": 1,
            "userId": 1,
            "userName": "admin",
            "userRole": 0,
            "userType": 0
        }
        res = self.session.post(
            url=url,
            data=json.dumps(data),
            headers=self.headers)
        print("获取组列表", flush=True)
        print(res.json(), flush=True)
        print(res.status_code, flush=True)
        return res.json()

    def get_cluster_list(self, group_id):
        """获取某一组下的集群列表

        :param group_id:
        :return:
        """
        url = self.redis_manager_domain + "/cluster/getClusterList/%d" % group_id
        res = self.session.get(url=url, headers=self.headers)
        print("获取某一组下的集群列表", flush=True)
        print(res.json(), flush=True)
        print(res.status_code, flush=True)
        return res.json()

    def validate_redis_node(self):
        """验证redis节点是否正常

        :return:
        """
        url = self.redis_manager_domain + "/validate/redisNode"
        data = {
            "redisPassword": None,
            "redisNode": {
                "host": "10.20.1.210",
                "port": "6379"
            }
        }
        res = self.session.post(
            url=url,
            data=json.dumps(data),
            headers=self.headers)
        print("验证redis节点", flush=True)
        print(res.json(), flush=True)
        print(res.status_code, flush=True)
        return res.json()

    def validate_cluster_name(self, cluster_name):
        """验证redis集群，获取相关信息

        :param cluster_name:
        :return:
        """
        url = self.redis_manager_domain + "/cluster/validateClusterName/%s" % cluster_name
        res = self.session.get(url=url, headers=self.headers)
        print("验证redis集群", flush=True)
        print(res.json(), flush=True)
        print(res.status_code, flush=True)
        return res.json()

    def update_cluster(self, cluster_name, node_list, nodes):
        """更新集群信息

        :param cluster_name: 集群名称
        :param node_list: redis节点列表， list类型，如[{"value": "10.20.1.210:6379"}]
        :param nodes: redis节点，str类型，如"10.20.1.210:6379,"
        :return:
        """
        try:
            # self.validate_redis_node()
            cluster_info = self.validate_cluster_name(
                cluster_name=cluster_name)
            url = self.redis_manager_domain + "/cluster/updateCluster"
            data = {
                "channelIds": cluster_info['data']['channelIds'],
                "clusterId": cluster_info['data']['clusterId'],
                "clusterKnownNodes": cluster_info['data']['clusterKnownNodes'],
                "clusterName": cluster_info['data']['clusterName'],
                "clusterSize": cluster_info['data']['clusterSize'],
                "clusterSlotsAssigned": cluster_info['data']['clusterSlotsAssigned'],
                "clusterSlotsFail": cluster_info['data']['clusterSlotsFail'],
                "clusterSlotsOk": cluster_info['data']['clusterSlotsOk'],
                "clusterSlotsPfail": cluster_info['data']['clusterSlotsPfail'],
                "clusterState": cluster_info['data']['clusterState'],
                "clusterToken": cluster_info['data']['clusterToken'],
                "dbSize": cluster_info['data']['dbSize'],
                "groupId": cluster_info['data']['groupId'],
                "image": cluster_info['data']['image'],
                "initialized": cluster_info['data']['initialized'],
                "installationEnvironment": cluster_info['data']['installationEnvironment'],
                "installationType": cluster_info['data']['installationType'],
                "masterOk": cluster_info['data']['masterOk'],
                "nodeList": node_list,
                "nodes": nodes,
                "os": cluster_info['data']['os'],
                "redisMode": cluster_info['data']['redisMode'],
                "redisPassword": cluster_info['data']['redisPassword'],
                "redisVersion": cluster_info['data']['redisVersion'],
                "ruleIds": cluster_info['data']['ruleIds'],
                "sentinelMasters": cluster_info['data']['sentinelMasters'],
                "sentinelOk": cluster_info['data']['sentinelOk'],
                "totalExpires": cluster_info['data']['totalExpires'],
                "totalKeys": cluster_info['data']['totalKeys'],
                "totalUsedMemory": cluster_info['data']['totalUsedMemory'],
                "updateTime": cluster_info['data']['updateTime'],
                "userId": cluster_info['data']['userId']}
            res = self.session.post(
                url=url,
                data=json.dumps(data),
                headers=self.headers)
            print("更新集群信息", flush=True)
            print(res.json(), flush=True)
            print(res.status_code, flush=True)
            return res.json()
        except Exception as e:
            print(e, flush=True)


if __name__ == '__main__':
    RM = RedisManager()
    RM.login()
    RM.get_group_list()
    RM.get_cluster_list(group_id=2)
    RM.update_cluster(cluster_name="jcss-share-redis",
                      node_list=[{"value": "10.20.1.210:6379"}],
                      nodes="10.20.1.210:6379,")
